<template>
  <div class="common-defect-page">
    <div class="card-stack">
      <el-card class="card-block breadcrumb-card">
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>质量管理</el-breadcrumb-item>
          <el-breadcrumb-item>缺陷管理</el-breadcrumb-item>
          <el-breadcrumb-item>常见缺陷</el-breadcrumb-item>
        </el-breadcrumb>
      </el-card>
      <el-card class="card-block query-card">
          <el-form class="filter-form" :inline="true" :model="queryForm" label-width="auto">
            <el-form-item label="缺陷编号">
              <el-input v-model="queryForm.commonefectscard" placeholder="请输入缺陷编号" clearable />
            </el-form-item>
            <el-form-item label="缺陷名称">
              <el-input v-model="queryForm.commonefectsname" placeholder="请输入缺陷名称" clearable />
            </el-form-item>
            <el-form-item label="缺陷类型">
              <el-select v-model="queryForm.defecttypeid" placeholder="请选择缺陷类型" clearable>
                <el-option
                  v-for="item in defectTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="缺陷位置">
              <el-select v-model="queryForm.defectlocationid" placeholder="请选择缺陷位置" clearable>
                <el-option
                  v-for="item in defectLocationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="缺陷等级">
              <el-select v-model="queryForm.defectlevelid" placeholder="请选择缺陷等级" clearable>
                <el-option
                  v-for="item in defectLevelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="queryForm.commonefectsstate" placeholder="请选择缺陷状态" clearable>
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      <el-card class="card-block table-card">
          <div class="table-toolbar">
            <div>
              <el-button type="primary" @click="startCreate">新增</el-button>
              <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">
                删除
              </el-button>
            </div>
            <div class="table-total">共 {{ pagination.totalCount }} 条</div>
          </div>
          <el-table
            :data="tableData"
            border
            stripe
            style="width: 100%"
            :loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="index" label="序号" width="70" />
            <el-table-column prop="commonefectscard" label="缺陷编号" min-width="120" />
            <el-table-column prop="commonefectsname" label="缺陷名称" min-width="140" />
            <el-table-column prop="defecttypename" label="缺陷类型" min-width="120" />
            <el-table-column prop="defectlocationname" label="缺陷位置" min-width="120" />
            <el-table-column prop="defectlevelname" label="缺陷等级" min-width="120" />
            <el-table-column prop="commonefectsnote" label="缺陷描述" min-width="160" show-overflow-tooltip />
            <el-table-column label="状态" width="110">
              <template #default="{ row }">
                <el-tag :type="row.commonefectsstate === '启用' ? 'success' : 'info'">
                  {{ row.commonefectsstate }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="commonefectsdes" label="备注" min-width="140" show-overflow-tooltip />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link size="small" @click="startEdit(row)">编辑</el-button>
                <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :total="pagination.totalCount"
              :page-sizes="[10, 20, 30, 50]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      <!-- 新增/编辑弹框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="formMode === 'create' ? '新增缺陷' : '编辑缺陷'"
        width="600px"
        :close-on-click-modal="false"
        @close="resetForm"
      >
        <el-form ref="formRef" :model="formModel" :rules="rules" label-width="90px">
          <el-form-item label="缺陷编码" prop="commonefectscard">
            <el-input v-model="formModel.commonefectscard" :disabled="formModel.useSystemCode" placeholder="请输入缺陷编码">
              <template #suffix>
                <span class="system-flag">
                  <span>系统编号</span>
                  <el-switch
                    v-model="formModel.useSystemCode"
                    size="small"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                    @change="handleSystemCodeChange"
                  />
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="缺陷名称" prop="commonefectsname">
            <el-input v-model="formModel.commonefectsname" placeholder="请输入缺陷名称" />
          </el-form-item>
          <el-form-item label="缺陷类型" prop="defecttypeid">
            <el-select v-model="formModel.defecttypeid" placeholder="请选择缺陷类型" style="width: 100%">
              <el-option
                v-for="item in defectTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="缺陷位置" prop="defectlocationid">
            <el-select v-model="formModel.defectlocationid" placeholder="请选择缺陷位置" style="width: 100%">
              <el-option
                v-for="item in defectLocationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="缺陷等级" prop="defectlevelid">
            <el-select v-model="formModel.defectlevelid" placeholder="请选择缺陷等级" style="width: 100%">
              <el-option
                v-for="item in defectLevelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="commonefectsstate">
            <el-radio-group v-model="formModel.commonefectsstate">
              <el-radio-button label="启用" />
              <el-radio-button label="禁用" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="缺陷描述" prop="commonefectsnote">
            <el-input v-model="formModel.commonefectsnote" type="textarea" :rows="3" placeholder="请输入缺陷描述" />
          </el-form-item>
          <el-form-item label="备注" prop="commonefectsdes">
            <el-input v-model="formModel.commonefectsdes" type="textarea" :rows="2" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight } from "@element-plus/icons-vue";
import { computed, onMounted, reactive, ref } from "vue";
import https from "@/Http/http";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";

type ApiEnum = -1 | 0 | 1;

interface ApiPageingResponse<T> {
  code: ApiEnum;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

interface ApiResultResponse<T> {
  code: ApiEnum;
  msg: string;
  data: T;
}

interface CommonDefectDTO {
  id: number;
  commonefectscard: string;
  commonefectsname: string;
  defecttypeid: number;
  defectlevelid: number;
  defectlocationid: number;
  commonefectsstate: string;
  commonefectsnote: string;
  commonefectsdes: string;
  defectlevelname: string;
  defectlocationname: string;
  defecttypename: string;
}

interface CommonDefectRow extends CommonDefectDTO {
  index: number;
}

const loading = ref(false);
const tableData = ref<CommonDefectRow[]>([]);
const multipleSelection = ref<CommonDefectRow[]>([]);
const dialogVisible = ref(false);

const statusOptions = [
  { label: "启用", value: "启用" },
  { label: "禁用", value: "禁用" },
];

interface DefectTypeItem {
  id: number;
  defecttypename: string;
}

interface DefectLocationItem {
  id: number;
  defectlocationname: string;
}

interface DefectLevelItem {
  id: number;
  defectlevelname: string;
}

const dropdownSource = reactive({
  type: [] as DefectTypeItem[],
  location: [] as DefectLocationItem[],
  level: [] as DefectLevelItem[],
});

const defectTypeOptions = computed(() =>
  dropdownSource.type.map((item) => ({
    label: item.defecttypename,
    value: item.id,
  })),
);

const defectLocationOptions = computed(() =>
  dropdownSource.location.map((item) => ({
    label: item.defectlocationname,
    value: item.id,
  })),
);

const defectLevelOptions = computed(() =>
  dropdownSource.level.map((item) => ({
    label: item.defectlevelname,
    value: item.id,
  })),
);

const queryForm = reactive({
  commonefectscard: "",
  commonefectsname: "",
  defecttypeid: undefined as number | undefined,
  defectlocationid: undefined as number | undefined,
  defectlevelid: undefined as number | undefined,
  commonefectsstate: "",
});

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

const formMode = ref<"create" | "edit">("create");
const formRef = ref<FormInstance>();
const formModel = reactive({
  id: undefined as number | undefined,
  commonefectscard: "",
  commonefectsname: "",
  defecttypeid: undefined as number | undefined,
  defectlocationid: undefined as number | undefined,
  defectlevelid: undefined as number | undefined,
  commonefectsstate: "启用",
  commonefectsnote: "",
  commonefectsdes: "",
  useSystemCode: true,
});

const rules: FormRules = {
  commonefectscard: [{ required: true, message: "请输入缺陷编码", trigger: "blur" }],
  commonefectsname: [{ required: true, message: "请输入缺陷名称", trigger: "blur" }],
  defecttypeid: [{ required: true, message: "请选择缺陷类型", trigger: "change" }],
  defectlocationid: [{ required: true, message: "请选择缺陷位置", trigger: "change" }],
  defectlevelid: [{ required: true, message: "请选择缺陷等级", trigger: "change" }],
};

const generateCode = () => {
  const now = new Date();
  return `QXBH${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, "0")}${now
    .getDate()
    .toString()
    .padStart(2, "0")}${now.getHours().toString().padStart(2, "0")}${now.getMinutes().toString().padStart(2, "0")}${now
    .getSeconds()
    .toString()
    .padStart(2, "0")}`;
};

const handleSystemCodeChange = () => {
  if (formModel.useSystemCode) {
    formModel.commonefectscard = generateCode();
  } else {
    formModel.commonefectscard = "";
  }
};

const fetchDropdownOptions = async () => {
  try {
    const [typeRes, locationRes, levelRes] = await Promise.all([
      https.Reads.get<ApiPageingResponse<DefectTypeItem>>("/Defect/DefectType", {
        params: { pageindex: 1, pagesize: 999 },
      }),
      https.Reads.get<ApiPageingResponse<DefectLocationItem>>("/Defect/DefectLocation", {
        params: { pageindex: 1, pagesize: 999 },
      }),
      https.Reads.get<ApiPageingResponse<DefectLevelItem>>("/Defect/DefectLevel", {
        params: { pageindex: 1, pagesize: 999 },
      }),
    ]);

    dropdownSource.type = typeRes.data.data ?? [];
    dropdownSource.location = locationRes.data.data ?? [];
    dropdownSource.level = levelRes.data.data ?? [];
  } catch (error) {
    console.error(error);
    ElMessage.error("获取下拉数据失败");
  }
};

const fetchTableData = async () => {
  loading.value = true;
  try {
    const { data } = await https.Reads.get<ApiPageingResponse<CommonDefectDTO>>("/Defect/CommonDefectList", {
      params: {
        pagesize: pagination.pageSize,
        pageindex: pagination.pageIndex,
        commonefectscard: queryForm.commonefectscard,
        commonefectsname: queryForm.commonefectsname,
        defecttypeid: queryForm.defecttypeid,
        defectlocationid: queryForm.defectlocationid,
        defectlevelid: queryForm.defectlevelid,
        commonefectsstate: queryForm.commonefectsstate,
      },
    });
    if (data.code !== 1) {
      throw new Error(data.msg || "查询失败");
    }
    pagination.totalCount = data.totalCount || 0;
    tableData.value = (data.data || []).map((item, index) => ({
      ...item,
      index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1,
    }));
  } catch (error: any) {
    console.error(error);
    ElMessage.error(error.message || "获取常见缺陷失败");
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleReset = () => {
  queryForm.commonefectscard = "";
  queryForm.commonefectsname = "";
  queryForm.defecttypeid = undefined;
  queryForm.defectlocationid = undefined;
  queryForm.defectlevelid = undefined;
  queryForm.commonefectsstate = "";
  handleQuery();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchTableData();
};

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page;
  fetchTableData();
};

const handleSelectionChange = (rows: CommonDefectRow[]) => {
  multipleSelection.value = rows;
};

const resetForm = () => {
  formRef.value?.resetFields();
  formMode.value = "create";
  formModel.id = undefined;
  formModel.useSystemCode = true;
  handleSystemCodeChange();
  formModel.commonefectsstate = "启用";
  formModel.defecttypeid = undefined;
  formModel.defectlocationid = undefined;
  formModel.defectlevelid = undefined;
  formModel.commonefectsnote = "";
  formModel.commonefectsdes = "";
};

const startCreate = () => {
  formMode.value = "create";
  resetForm();
  dialogVisible.value = true;
};

const startEdit = (row: CommonDefectDTO) => {
  formMode.value = "edit";
  formModel.id = row.id;
  formModel.commonefectscard = row.commonefectscard;
  formModel.commonefectsname = row.commonefectsname;
  formModel.defecttypeid = row.defecttypeid;
  formModel.defectlocationid = row.defectlocationid;
  formModel.defectlevelid = row.defectlevelid;
  formModel.commonefectsstate = row.commonefectsstate;
  formModel.commonefectsnote = row.commonefectsnote;
  formModel.commonefectsdes = row.commonefectsdes;
  formModel.useSystemCode = false;
  dialogVisible.value = true;
};

const buildPayload = () => ({
  id: formModel.id,
  commonefectscard: formModel.commonefectscard,
  commonefectsname: formModel.commonefectsname,
  defecttypeid: formModel.defecttypeid,
  defectlocationid: formModel.defectlocationid,
  defectlevelid: formModel.defectlevelid,
  commonefectsstate: formModel.commonefectsstate,
  commonefectsnote: formModel.commonefectsnote,
  commonefectsdes: formModel.commonefectsdes,
});

const submitForm = async () => {
  const payload = buildPayload();
  if (formMode.value === "create") {
    return https.Writes.post<ApiResultResponse<number>>("/CommonDefects/CommonDefectAdd", payload);
  }
  return https.Writes.put<ApiResultResponse<number>>("/CommonDefects/CommonDefectUpdate", payload);
};

const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    try {
      const response = await submitForm();
      if (response.data.code !== 1) {
        throw new Error(response.data.msg || "保存失败");
      }
      ElMessage.success("保存成功");
      dialogVisible.value = false;
      resetForm();
      fetchTableData();
    } catch (error: any) {
      console.error(error);
      ElMessage.error(error.message || "保存失败");
    }
  });
};

const deleteCommonDefect = (id: number) =>
  https.Writes.request<ApiResultResponse<number>>({
    method: "delete",
    url: "/CommonDefects/CommonDefectDel",
    data: { id },
  });

const handleDelete = (row: CommonDefectRow) => {
  ElMessageBox.confirm(`确认删除缺陷【${row.commonefectsname}】吗？`, "提示", {
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteCommonDefect(row.id);
        if (res.data.code !== 1) {
          throw new Error(res.data.msg || "删除失败");
        }
        ElMessage.success("删除成功");
        fetchTableData();
      } catch (error: any) {
        console.error(error);
        ElMessage.error(error.message || "删除失败");
      }
    })
    .catch(() => {});
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) return;
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条数据吗？`, "提示", {
    type: "warning",
  })
    .then(async () => {
      try {
        await Promise.all(
          multipleSelection.value.map((item) =>
            deleteCommonDefect(item.id),
          ),
        );
        ElMessage.success("批量删除成功");
        fetchTableData();
      } catch (error: any) {
        console.error(error);
        ElMessage.error(error.message || "批量删除失败");
      }
    })
    .catch(() => {});
};

onMounted(async () => {
  handleSystemCodeChange();
  await fetchDropdownOptions();
  fetchTableData();
});
</script>

<style scoped>
.common-defect-page {
  min-height: calc(100vh - 60px);
  padding: 16px;
  background: linear-gradient(135deg, #f3f5ff 0%, #fef5f5 45%, #fdf8ff 100%);
}

.card-stack {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.card-block {
  width: 100%;
  background: linear-gradient(145deg, rgba(255, 255, 255, 0.85), rgba(242, 248, 255, 0.78));
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 10px 30px rgba(15, 36, 70, 0.08);
  backdrop-filter: blur(12px);
  border-radius: 12px;
}

.query-card,
.table-card {
  width: 100%;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.table-total {
  color: #909399;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
}

.system-flag {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #909399;
}
</style>

